const express = require("express");
const shot = express();
const puppeteer = require('puppeteer');
const fs = require("fs");
const url = require("url")
const { PDFDocument } = require('pdf-lib');
function addmk(addr) {
    fs.mkdir(addr, function (err) {
        if (err) {
            return console.error("已有");
        }
    });
}
shot.use(express.static(__dirname+'/png_toolbook'))
// shot.use(express.static('public'));

shot.get('/', (req, res) => {try{
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    console.log("加载中")
    res.write("<span>生成png请输入http://localhost:3000/img/png+目标地址</span><br>"
        + "<span>生成pdf请输入http://localhost:3000/img/pdf+目标地址</span>")
}catch(e){res.send(e)}
})

//输入网址生成png
shot.get('/img/png/*', function (req, res) {
    try{addmk("./png_shot/")
    var str = new url.parse(req.url).path;
    var add = str.slice(9);                      //截取url得到网址
    var fileName2 = add;
    var fileName1 = fileName2.slice(8);
    var fileName = fileName1.replace('/', '_');    //使用www.后前八个字符作为文件名
    res.sendFile(__dirname + "/png_shot/" + fileName + ".png", function (err, data) {
        if (err) {
            (async () => {
                const browser = await puppeteer.launch();
                const page = await browser.newPage();
                await page.goto(add);//打开对应网址
                await page.screenshot({ path: "./png_shot/" + fileName + ".png", fullPage: true });//截图
                await browser.close();
                await res.sendFile(__dirname + "/png_shot/" + fileName + ".png");  //将截图返回在浏览器上
            })()
        }
        else console.log(data)
    })}catch(e){res.send(e)}
})

//输入网址生成pdf
shot.get('/img/pdf/*', function (req, res) {
    try{
        addmk("./PDF_shot/")
    var str = new url.parse(req.url).path;
    var pdf_add = str.slice(9);                      //截取url得到网址
    var pdf_fileName2 = pdf_add;
    var pdf_fileName1 = pdf_fileName2.slice(8);
    var pdf_fileName = pdf_fileName1.replace('/', '_');
    res.sendFile(__dirname + "/PDF_shot/" + pdf_fileName + ".pdf", function (err, data) {
        if (err) {
            (async () => {
                const browser = await puppeteer.launch();
                const page = await browser.newPage();
                await page.goto(pdf_add);
                await page.pdf({ path: "./PDF_shot/" + pdf_fileName + '.pdf' });
                await browser.close();
                await res.sendFile(__dirname + "/PDF_shot/" + pdf_fileName + ".pdf");
            })()
        }
        else console.log(data)
    });      //使用www.后前八个字符作为文件名 
    }catch(e){res.send(e)}
    
})
//生成工具书
shot.get('/toolbook/pdf', function (req, res) {
    try {
        const url = `https://chrisniael.gitbooks.io/gitbook-documentation/content/build/ebookconvert.html`;
    addmk("./PDF_toolbook/");
    res.sendFile(__dirname + "/git工具书.pdf", function (err, data) {
        if (err) {
            (async () => {
                console.log('Start visit');
                const brower = await puppeteer.launch({
                    args: ['--no-sandbox'],
                    dumpio: false
                });
                const page = await brower.newPage()   // 开启一个新页面
                await page.goto(url, {
                    waitUntil: 'networkidle2'  // 网络空闲说明已加载完毕
                });
                await page.waitForSelector('.summary');
                const result = await page.evaluate(() => {
                    // 拿到页面上的jQuery
                    var $ = window.$;
                    var links = [];
                    var items = $('ul.summary li');
                    if (items.length >= 1) {
                        items.each((index, item) => {
                            let it = $(item)
                            let chapterId = it.find('a').find("b").prop('innerText')
                            let title = it.find('a').prop('innerText')
                            let poster = it.find('a').attr('href')
                            links.push({
                                chapterId,
                                title,
                                poster
                            })
                        });
                    }
                    return links
                });
                var mid_poster = result;
                var arr = [];
                mid_poster = mid_poster.filter(value => Object.keys(value).length !== 0)
                for (let key in mid_poster) {
                    let x = mid_poster[key].poster;
                    let y = mid_poster[key].title;
                    if (x.length > 0 && x.slice(0, 3) == "../") {
                        x = "https://chrisniael.gitbooks.io/gitbook-documentation/content" + x.slice(2)
                        const page = await brower.newPage();
                        await page.goto(x);

                        if (key == 1) {
                            await page.$eval('.navigation-next',
                                (el, value) => el.setAttribute('style', value),
                                'display:none'
                            )
                        }
                        else if (key == mid_poster.length - 1) {
                            await page.$eval('.navigation-prev',
                                (el, value) => el.setAttribute('style', value),
                                'display:none'
                            )
                        }
                        else {
                            await page.$eval('.navigation-next',
                                (el, value) => el.setAttribute('style', value),
                                'display:none'
                            )
                            await page.$eval('.navigation-prev',
                                (el, value) => el.setAttribute('style', value),
                                'display:none'
                            )
                        }
                        await page.$eval('.book-summary',
                            (el, value) => el.setAttribute('style', value),
                            'display:none'
                        )
                        await page.$eval('body',
                            (el, value) => el.setAttribute('style', value),
                            'margin:0; padding:0; '
                        )
                        await page.$eval('.book-header',
                            (el, value) => el.setAttribute('style', value),
                            'display:none'
                        )
                        await page.$eval('.book-body',
                            (el, value) => el.setAttribute('style', value),
                            'position: relative;left:10px'
                        )
                        await page.evaluate((y) => {
                            var addheader = document.getElementById("section-");
                            console.log(addheader)
                            addheader.innerHTML = "<h1>" + y + "</h1>" + addheader.innerHTML
                        }, y);


                        await page.pdf({ path: "./pdf_toolbook/" + x.slice(60).replace(/\//g, '_') + '.pdf' });
                        await page.close();
                        arr.push("./pdf_toolbook/" + x.slice(60).replace(/\//g, '_') + ".pdf")
                    }
                }
                brower.close();
                let contentPages
                let content
                const doc = await PDFDocument.create();
                for (let num in arr) {
                    content = await PDFDocument.load(fs.readFileSync(arr[num]));
                    console.log(arr[num])
                    contentPages = await doc.copyPages(content, content.getPageIndices());
                    for (const page of contentPages) {
                        doc.addPage(page);
                    }
                }
                fs.writeFileSync('./git工具书.pdf', await doc.save());
                await res.sendFile(__dirname + "/git工具书.pdf")
            })();
        }
        else {
            console.log(data)
        }
    })
    } catch (error) {
        res.send(error)
    }
})

//生成png工具书
shot.get("/toolbook/png", function (req, res) {
    try {
        const url = `https://chrisniael.gitbooks.io/gitbook-documentation/content/build/ebookconvert.html`;
        res.setHeader('Content-Type', 'text/html;charset=utf-8');
        (async () => {
            // 启动一个浏览器
            const brower = await puppeteer.launch({
            });
            const page = await brower.newPage()   // 开启一个新页面
            await page.goto(url, {
                waitUntil: 'networkidle2'  // 网络空闲说明已加载完毕
            });
            await page.waitForSelector('.summary');
            // 结果
            const result = await page.evaluate(() => {
                // 拿到页面上的jQuery
                var $ = window.$;
                var links = [];
                var items = $('ul.summary li');
                if (items.length >= 1) {
                    items.each((index, item) => {
                        let it = $(item)
                        let chapterId = it.find('a').find("b").prop('innerText')
                        let title = it.find('a').prop('innerText')
                        let poster = it.find('a').attr('href')
                        links.push({
                            chapterId,
                            title,
                            poster
                        })
                    });
                }
                return links     //得到遍历后的标题和链接
            });
            var mid_poster = result;
            var imgarr = '';
            mid_poster = mid_poster.filter(value => Object.keys(value).length !== 0)//去掉空对象
            fs.mkdir("./png_toolbook/", function (err) {
                if (err) {
                    for(let i in mid_poster){
                        let x = mid_poster[i].poster;
                        if (x.length > 0 && x.slice(0, 3) == "../") {
                        x = "https://chrisniael.gitbooks.io/gitbook-documentation/content" + x.slice(2)
                        imgarr = imgarr + "<img src=" + "'http://localhost:3000/" + x.slice(60).replace(/\//g, '_') + ".png'><br>"
                    }}
                }
                res.write(imgarr)
            });
            for (var key in mid_poster) {               //遍历链接生成截图
                let x = mid_poster[key].poster;
                if (x.length > 0 && x.slice(0, 3) == "../") {
                    x = "https://chrisniael.gitbooks.io/gitbook-documentation/content" + x.slice(2)
                    const page = await brower.newPage();
                    await page.goto(x);
                    console.log(x);
                    let body = await page.$('#section-');
                    imgarr = imgarr + "<img src=" + "'http://localhost:3000/" + x.slice(60).replace(/\//g, '_') + ".png'><br>"
                    await body.screenshot({
                        path: "./png_toolbook/" + x.slice(60).replace(/\//g, '_') + '.png'
                    });
                    await page.close();
                }
            }
            brower.close();    //关闭网页
            await res.write(imgarr)
        })();
    } catch (error) {
        res.send(error)
    }
})
shot.listen(3000, function (err) {
    if (err) console.log(err);
    console.log("Server listening on 3000", 3000);
});
